package com.ted.hole2.config;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.ted.hole2.config.HoleService.RepositoryImpl;
import com.ted.hole2.config.HoleService.ServiceRepository;

/**
 * Hibernate 配置
 * 
 * @author Zhang Kangkang
 */
public class HibernateConfig {

    static EntityManager em;

    volatile static ConcurrentHashMap<Class<?>, ServiceRepository<?, ?>> CACHE_SERVICE = new ConcurrentHashMap<>();

    static {
        init();
    }

    public static void init() {
        EntityManagerFactory sessionFactory = Persistence.createEntityManagerFactory("hole");
        em = sessionFactory.createEntityManager();
    }

    @SuppressWarnings("unchecked")
    public static <T extends ServiceRepository<?, ?>, E> T getService(Class<E> cls, Class<T> serviceCls) {

        if (CACHE_SERVICE.get(cls) == null) {

            InvocationHandler handler = new ServiceProxy(new RepositoryImpl<>(cls, em));
            ServiceRepository<E, Long> service = (ServiceRepository<E, Long>)Proxy
                .newProxyInstance(RepositoryImpl.class.getClassLoader(), new Class[] {serviceCls}, handler);

            CACHE_SERVICE.put(cls, service);
            return (T)service;
        }
        return (T)CACHE_SERVICE.get(cls);
    }

}
